package com.zm.tools.util.core;

import org.apache.commons.lang3.StringUtils;

/**
 * 脱敏工具
 * @author zoum
 * @create 2018/9/18 14:33
 */
public class DesensitizationUtil {


    /**
     * 身份证脱敏
     * 默认展示前三后四
     * @param idCard
     * @return
     */
    public static String desensitizationIdCard(String idCard){
        int length;
        if (StringUtils.isBlank(idCard)
                || ((length = idCard.length()) != 15 && length != 18)){
            return idCard;
        }
        return idCard.substring(0,3) + getStar(length-7) + idCard.substring(idCard.length()-4,idCard.length());
    }

    /**
     * 身份证脱敏
     * (startIndex,endIndex] 隐藏
     * @param idCard
     * @return
     */
    public static String desensitizationIdCard(String idCard, int startIndex, int endIndex){
        startIndex = startIndex - 1;
        if (startIndex<0 || startIndex>idCard.length() || endIndex<0 || endIndex> idCard.length()){
            return desensitizationIdCard(idCard);
        }
        return idCard.substring(0,startIndex) + getStar(endIndex - startIndex) + idCard.substring(endIndex,idCard.length());
    }

    /**
     * 手机号脱敏
     * 默认展示前三后四
     * @param mobile
     * @return
     */
    public static String desensitizationMobile(String mobile){
        int length;
        if (StringUtils.isBlank(mobile) || (length = mobile.length()) < 11){
            return mobile;
        }

        return mobile.substring(0,3) + getStar(length - 7) + mobile.substring(length-4,length);
    }

    /**
     * 手机号脱敏
     * (startIndex,endIndex] 隐藏
     * @param mobile
     * @return
     */
    public static String desensitizationMobile(String mobile, int startIndex, int endIndex){
        int length;
        if (StringUtils.isBlank(mobile) || (length = mobile.length()) < 11){
            return mobile;
        }
        startIndex = startIndex - 1;
        if (startIndex < 0 || startIndex > length || endIndex < 0 || endIndex > length){
            return desensitizationMobile(mobile);
        }

        return mobile.substring(0, startIndex) + getStar(endIndex - startIndex) + mobile.substring(endIndex,length);
    }

    /**
     * 姓名脱敏, 两个字 ，第一个变*， 大于等于单个字的，显示首尾两字，中间加*
     * @param userName
     * @return
     */
    public static String desensitizationUserName(String userName){
        if (StringUtils.isBlank(userName)){
            return userName;
        }
        int length = userName.length();
        if (length == 1){
            return "*" + userName;
        }
        if (length == 2){
            return "*" + userName.charAt(length-1);
        }
        if (length>=3){
            return userName.charAt(0) + "*" + userName.charAt(length-1);
        }
        return "";
    }

    public static String getStar(int length){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append("*");
        }
        return sb.toString();
    }

}
